package day14.example;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * @author admin
 */
public class JDBCUtils {
    private static String URL = "jdbc:mysql://localhost:3306/text1";
    private static String USER = "root";
    private static String PASSWORD = "root";
    private static String DRIVER = "com.mysql.cj.jdbc.Driver";

    static {
        try {
            Properties properties = new Properties();
            ClassLoader classLoader = JDBCUtils.class.getClassLoader();
            java.net.URL res = classLoader.getResource("jdbc.properties");
            if (res != null) {
                String path = res.getPath();
                System.out.println(path);
                properties.load(new FileReader(path));
                URL = properties.getProperty("url");
                USER = properties.getProperty("user");
                PASSWORD = properties.getProperty("password");
                DRIVER = properties.getProperty("driver");
            }
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }

    public static void close(Statement statement, Connection connection) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(ResultSet resultSet, Statement statement, Connection connection) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        close(statement, connection);
    }
}
